package com.huishen.edrivenew.ui;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnGroupExpandListener;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.huishen.edrivenew.AppContext;
import com.huishen.edrivenew.Constants;
import com.huishen.edrivenew.R;
import com.huishen.edrivenew.adapter.AppoCoachListApdater;
import com.huishen.edrivenew.adapter.ClassListCoachApdater;
import com.huishen.edrivenew.adapter.ClassListSchoolApdater;
import com.huishen.edrivenew.adapter.ClassSchoolListener;
import com.huishen.edrivenew.adapter.TimeClassApointListener;
import com.huishen.edrivenew.adapter.TimeClassSchoolListener;
import com.huishen.edrivenew.base.BaseActivity;
import com.huishen.edrivenew.bean.CoachBean;
import com.huishen.edrivenew.bean.CoachListBean;
import com.huishen.edrivenew.bean.LessInfoBean;
import com.huishen.edrivenew.bean.LessonTimeBean;
import com.huishen.edrivenew.bean.LessonlistCoachBean;
import com.huishen.edrivenew.bean.LessonlistSchoolBean;
import com.huishen.edrivenew.bean.ListLessonTimeBean;
import com.huishen.edrivenew.bean.StudentBean;
import com.huishen.edrivenew.net.BitmapManager;
import com.huishen.edrivenew.net.JsonResponseHandler;
import com.huishen.edrivenew.net.NetApi;
import com.huishen.edrivenew.util.StringUtils;
import com.huishen.edrivenew.util.TLog;
import com.huishen.edrivenew.widget.CircleImageView;
import com.huishen.edrivenew.widget.MassageListener;
import com.huishen.edrivenew.widget.MessageDialog;

import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 新模式学时
 */
public class ClassListSchoolActivity extends BaseActivity implements OnRefreshListener2<ListView> {


    @InjectView(R.id.header_title)
    public TextView title;
    @InjectView(R.id.header_back)
    public ImageButton back;

    @InjectView(R.id.titlelist_list)
    public PullToRefreshListView list;

    @InjectView(R.id.f_appoint_photo)
    public CircleImageView headView;
    @InjectView(R.id.f_appoint_coachname)
    public TextView coachName;
    @InjectView(R.id.f_appoint_coachcar)
    public TextView coachPhone;

    // 学时信息
    @InjectView(R.id.moeny)
    public TextView smoney;
    @InjectView(R.id.moeny1)
    public TextView smoney1;
    @InjectView(R.id.stime)
    public TextView stime;

    @InjectView(R.id.time_text)
    public TextView stimeText;

    @InjectView(R.id.class_title_text)
    public TextView classInfotext;
    @InjectView(R.id.class_title_text2)
    public TextView classInfotext2;
    @InjectView(R.id.class_title)
    public View classInfo;
    @InjectView(R.id.f_app_coach)
    public View coaInfo;

    @InjectView(R.id.classInfolog)
    public TextView classInfolog;
    @InjectView(R.id.classInfolog_line)
    public ImageView classInfolog_line;

    private StudentBean bean;
    private int page = 1;

    private LessonlistSchoolBean lessonInfoBean = new LessonlistSchoolBean();

    private ClassListSchoolApdater adapter;

    private int index = 0;

    private MessageDialog mdialog;
    BitmapManager bmpManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_class_school);
        ButterKnife.inject(this);

        index = AppContext.getInstance().classActivityType;

        initView();

        setDate();
        // 请求数据
        // 请求第一页
        page = 1;
        request(page);
    }


    private void initView() {
        if (index == 1) {
            title.setText("评价管理");

            stimeText.setText("预约时间");

            classInfotext.setVisibility(View.GONE);
            classInfotext2.setVisibility(View.GONE);
            classInfo.setVisibility(View.GONE);
            coaInfo.setVisibility(View.GONE);
            classInfolog.setVisibility(View.GONE);
            classInfolog_line.setVisibility(View.GONE);
        } else if (index == 2) {
            title.setText("我的学时统计");
            classInfolog.setVisibility(View.GONE);
            classInfolog_line.setVisibility(View.GONE);
        } else {
            title.setText("我的学时统计");
        }
    }


    private void setDate() {

        bean = AppContext.getInstance().studentBean;
        if (bean == null) {
            return;
        }
        coachName.setText(bean.name);
        coachPhone.setText(bean.phone);

        // 设置头像
        if (!StringUtils.isEmpty(bean.path)) {
            bmpManager =
                    new BitmapManager(BitmapFactory.decodeResource(AppContext.getInstance()
                            .getResources(), R.drawable.photo_bg));
            bmpManager.loadBitmap(bean.path, headView);
        }

        smoney.setText(bean.money + "");
        smoney1.setText(bean.balance + "");
        stime.setText(bean.timeNum + "");
    }


    // 设置listview
    private void setListDate() {
        if (adapter != null) {
            reSetListDate();
            return;
        }
        adapter = new ClassListSchoolApdater(this, lessonInfoBean, listener);
        list.getRefreshableView().setAdapter(adapter);

        list.setMode(Mode.BOTH);
        list.setOnRefreshListener(this);
        setLoadMoreText(false);
    }

    private void reSetListDate() {
        setLoadMoreText(lessonInfoBean.hasDone);
        adapter.setData();
        adapter.notifyDataSetChanged();
    }


    private void setLoadMoreText(boolean isDone) {
        if (isDone) {
            list.getLoadingLayoutProxy(false, true).setPullLabel("已加载全部");
            list.getLoadingLayoutProxy(false, true).setRefreshingLabel("已加载全部");
            list.getLoadingLayoutProxy(false, true).setReleaseLabel("已加载全部");
        } else {
            list.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");
            list.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
            list.getLoadingLayoutProxy(false, true).setReleaseLabel("放开加载更多...");
        }
    }


    private ClassSchoolListener listener = new ClassSchoolListener() {

        @Override
        public void setOnClick(int type, int position, int code) {
            LessInfoBean bean = lessonInfoBean.rows.get(position);
            AppContext.getInstance().judgeBean = bean;

            if (type == 1) {
                // 取消
                actionCancel(code);
            } else if (type == 2) {
                // 评价
                Intent intent = new Intent(ClassListSchoolActivity.this, JudgeActivity.class);
                ClassListSchoolActivity.this.startActivity(intent);
            } else if (type == 3) {
                // 详情
                Intent intent = new Intent(ClassListSchoolActivity.this, DetialActivity.class);
                ClassListSchoolActivity.this.startActivity(intent);
            }
        }
    };


    private void request(int currpage) {
        if (currpage == 1) {
            showDialog();
        }
        NetApi.queryStuLessonAndDetailPage(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                try {
                    if (code == Constants.N_SUCCESS) {
                        // 获取list数据
                        JSONObject listObj = jsonObj.getJSONObject("lessonList");
                        LessonlistSchoolBean newList =
                                (LessonlistSchoolBean) LessonlistSchoolBean.parseJson(listObj);
                        lessonInfoBean.addDate(newList);
                        setListDate();
                        page++;
                    } else {
                        showToast("获取数据失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取数据失败！");
                }
                dismissDialog();
                list.onRefreshComplete();
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                list.onRefreshComplete();
                showToast("获取数据失败！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                list.onRefreshComplete();
                super.onSessionFailure();
            }
        }, currpage + "");
    }


    /**
     * 取消按钮响应
     */
    private void actionCancel(final int id) {
        mdialog = new MessageDialog(this, "您确定取消预约的时间吗？", "", true, new MassageListener() {
            @Override
            public void setCommitClick() {
                cancelAppoint(id);
            }

            @Override
            public void setCancelClick() {}
        });
        mdialog.show();
    }



    private void cancelAppoint(int id) {
        showDialog();
        NetApi.updateTrainLessonInfo(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                dismissDialog();
                try {
                    if (code == Constants.N_SUCCESS) {
                        showToast("取消成功！");
                        updateDate();
                    } else {
                        showToast("操作失败，请稍后再试！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("操作失败，请稍后再试！");
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("操作失败，请稍后再试！");
            }
            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, id);
    }


    // TODO
    private void updateDate() {
        toMain();
    }

    @OnClick(R.id.header_back)
    public void toMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(intent);
        this.finish();
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        page = 1;
        request(page);
    }


    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (lessonInfoBean.hasDone) {
            list.postDelayed(new Runnable() {
                @Override
                public void run() {
                    list.onRefreshComplete();
                }
            }, 1000);
        } else {
            request(page);
        }
    }

}
